import re
# from linkutil.util import read_json
from django.core.validators import EmailValidator, URLValidator
from django.core.exceptions import ValidationError
# from link.models import Link

import json


def read_json(path):
    try:
        with open(path, "r", encoding="utf-8") as file:
            data = json.load(file)
    except FileNotFoundError:
        pass #print(f"文件{path}未找到")
    except json.JSONDecodeError:
        pass #print(f"文件{path} 不是有效的json")
    else:
        # pass #print(data)
        return data
    
def is_country_in_list(country):
    countries = read_json(r"./data/country.json")
    if country in countries:
        return True
    return False


# 检查10位数字
def is_ten_digit_number(s):
    return bool(re.fullmatch(r'\d{10}', s))


# 检查email
def is_google_email(email):
    """
    校验用户邮箱格式是否合法。
    """
    validator = EmailValidator(message="邮箱格式无效")
    try:
        validator(email)
        return True
    except ValidationError as e:
        return False


# 获取URL和参数
def get_url_params(url):
    url = url.replace("\\", "")
    aurl, a = url.split("?")
    b = a.split("&")
    c = [bb.split("=")[0] for bb in b]
    return aurl, c


# 对比获取的url是否满足要求, False 不满足， True 满足
def check_final_url(url, params, finalUrl):
    #这里可以将参数问题和url问题暴露出来 
    
    finalUrl_url, finalUrl_params = get_url_params(finalUrl)
    if (finalUrl_url == url or finalUrl_url == url+"/" or finalUrl_url+"/" == url):
        for p in params:
            if p and p not in finalUrl_params:
                return False
        return True
    return False


# 检查参数
def check_params(params, option="add"):
    mcc_account = params.get("mcc_account")
    if not is_ten_digit_number(mcc_account):
        return False, "mcc_account 参数存在问题"
    google_account_number = params.get("google_account_number")
    if not is_ten_digit_number(google_account_number):
        return False, "google_account_number 参数存在问题"
    campaign_name = params.get("campaign_name")
    if not campaign_name:
        return False, "campaign_name 不为空"
    target_action = params.get("target_action")
    if not is_country_in_list(target_action):
        return False, "target_Nation 不可用"
    return True, ""


# 检查返回的url是否满足要求
def check_url(urls, red, url_identifiers):
    while True:
        try:
            if red > 0:
                final_url = urls[red-1][0]
            else:
                final_url = urls[-1][0]
        except:
            final_url = urls[-1][0]
        if "?" in final_url:
            break
        else:
            final_url = urls[-2][0]
            break
    flag = False
    if url_identifiers:
        url_identifiers = url_identifiers.replace(" ", "")
        url_identifiers = url_identifiers.replace("，", ",")
        url_identifiers = url_identifiers.split(",")
        u = url_identifiers[0]
        p = url_identifiers[1:]
        # pass #print(final_url)
        # pass #print("u, p", u, p)
        if not check_final_url(u, p, final_url):
            # TODO 写日志
            final_url = "URL Identifiers 校验不通过，抓取的链接不合理\n" + final_url
            flag = False
        else:
            # TODO 写日志
            flag = True
            final_url = final_url.split("?")[-1]
            final_url = "{lpurl}?" +final_url
    else:
        flag = True
        final_url = final_url.split("?")[-1]
        final_url = "{lpurl}?" +final_url
    return flag, final_url


# 参数检查
def check_link_params(params):
    # 首先判断参数是否齐全
    # 参数校验  
    required_fields = [
        "MCCName", "UserEmail", "MCCAccount", "GoogleAccount",
        "CampaignName", "finalUrl", "OfferLink", "TargetNation", 
        "URLldentifiers", "InterVal", "Swith"
    ]

    missing_fields = [field for field in required_fields if field not in params]

    if missing_fields:
        return -1 # 参数不全 
    
    # 其次判断参数是否合法
    # 校验邮箱格式
    try:
        EmailValidator(message="邮箱格式无效")(params["UserEmail"])
    except :
        return -2 # 参数格式错误

    # 校验 URL 格式
    url_fields = ["OfferLink"]
    for url_field in url_fields:
        try:
            URLValidator(message=f"{url_field} 格式无效")(params[url_field])
        except:
            return -2 # 参数格式错误

    # 最后判断参数是否满足要求
    link = None
    # link = Link.objects.get(OfferLink=params["OfferLink"])
    if link:
        return -3 # lianjie 已存在
    return 1 # 参数合法